package com.pudu.mydemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanyp on 2016/8/26.
 */
public class DrawRaderView extends SurfaceView implements SurfaceHolder.Callback{

    public DrawRaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DrawRaderView(Context context) {
        super(context);
        init();
    }

    public DrawRaderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if(null == mDrawThread) {
            mDrawThread = new DrawThread();
            mDrawThread.start();

            Canvas canvas = holder.lockCanvas();
            DrawUseSurface(canvas);
            holder.unlockCanvasAndPost(canvas);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if(null != mDrawThread) {
            mDrawThread.exit();
            mDrawThread = null;
        }
    }


    public void init()
    {
        mHolder = this.getHolder();
        mHolder.addCallback(this);

        mLinePaint = new Paint();
        mLinePaint.setAntiAlias(true);
        mLinePaint.setColor(Color.RED);
        mLinePaint.setStyle(Paint.Style.STROKE);
        mLinePaint.setStrokeWidth(1);

        mPaintText = new Paint();
        mPaintText.setStrokeWidth(1);
        mPaintText.setTextSize(20);
        mPaintText.setColor(Color.RED);
        mPaintText.setTextAlign(Paint.Align.LEFT);

        mMyPaintText = new Paint();
        mMyPaintText.setStrokeWidth(1);
        mMyPaintText.setTextSize(20);
        mMyPaintText.setColor(Color.WHITE);
        mMyPaintText.setTextAlign(Paint.Align.LEFT);

    }

    public static final int MSG_INVALIDATE = 0;

    SurfaceHolder mHolder;
    private DrawThread mDrawThread;
    private Looper mLooper;
    private Handler mHandler;
    class DrawThread extends Thread {
        @Override
        public void run() {
            Looper.prepare();

            mLooper = Looper.myLooper();

            mHandler = new Handler(){
                public void handleMessage (Message msg) {
                    switch(msg.what) {
                        case MSG_INVALIDATE: {
                            Canvas canvas = null;

                            try {
                                if (null != mHolder) {
                                    canvas = mHolder.lockCanvas();
                                    DrawUseSurface(canvas);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                if (null != mHolder) {
                                    try {
                                        mHolder.unlockCanvasAndPost(canvas);
                                    }catch(Exception e)
                                    {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            };

            Looper.loop();
        }

        public void exit() {
            if (mLooper != null) {
                mLooper.quit();
                mLooper = null;
            }
        }
    }

    public void DrawUseSurface(Canvas canvas)
    {
        Log.i("vvvv", "scale:"+  scale);
        canvas.drawColor(Color.BLACK);

        DrawMapInfo(canvas);

        DrawCoordinates(canvas);

        DrawRegion(canvas);

        DrawAllMeasureData(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        nWidth = MeasureSpec.getSize(widthMeasureSpec);
        nHeight = MeasureSpec.getSize(heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        nHeight = h;
        nWidth = w;
    }

    int nHeight = 0;
    int nWidth = 0;

    Paint mLinePaint;
    Paint mPaintText;
    Paint mMyPaintText;
    double scale = 1;
    int mRectRange = 5;

    public void DrawMapInfo(Canvas canvas)
    {
        String str = String.format("scale:%f", (float)scale);
        canvas.drawText(str,30, 30, mPaintText);

        str = String.format("Height:%d Width:%d", nHeight, nWidth);
        canvas.drawText(str,30, 60, mPaintText);
    }

    public void DrawRegion(Canvas canvas)
    {
        canvas.drawCircle(nWidth/2, nHeight/2, (float) (50*scale), mLinePaint);

        String str = String.format("%d", 50);
        canvas.drawText(str,nWidth/2 + (float) (50*scale), nHeight/2, mMyPaintText);

        canvas.drawCircle(nWidth/2, nHeight/2, (float) (150*scale), mLinePaint);
        str = String.format("%d", 150);
        canvas.drawText(str,nWidth/2 + (int)(150*scale), nHeight/2, mMyPaintText);

        canvas.drawCircle(nWidth/2, nHeight/2, (float) (300*scale), mLinePaint);
        str = String.format("%d", 300);
        canvas.drawText(str,nWidth/2 + (int)(300*scale), nHeight/2, mMyPaintText);
    }

    public void DrawCoordinates(Canvas canvas)
    {
        canvas.drawLine(0, nHeight/2, nWidth, nHeight/2, mLinePaint);
        canvas.drawText("X 轴",nWidth - 50 , nHeight/2, mMyPaintText);

        canvas.drawLine(nWidth/2, 0, nWidth/2, nHeight, mLinePaint);
        canvas.drawText("Y 轴",nWidth/2 -50 , nHeight - 50, mMyPaintText);
    }

    List<rplidar_node_t> mlsDatas = new ArrayList<rplidar_node_t>();
    public void showData(List<rplidar_node_t> lsDatas )
    {
        try {

            mlsDatas.clear();
            Log.i("ooooo", "lsDatas" + lsDatas.size());
            mlsDatas.addAll(lsDatas);
        }catch(Exception e)
        {
            e.printStackTrace();
        }

        if (mHandler != null) {
            mHandler.sendEmptyMessage(MSG_INVALIDATE);
        }

    }

    public void DrawAllMeasureData(Canvas canvas)
    {
        if( mlsDatas == null)
        {
            return;
        }
        try {
            for (int i = 0; i < mlsDatas.size(); i++) {
                rplidar_node_t Obj = mlsDatas.get(i);

                RectF rect = getPointRect(Obj);
                canvas.drawRect(rect, mLinePaint);
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private RectF getPointRect(rplidar_node_t obj)
    {

        int x = (int) (nWidth/2 + obj.ptX*scale);
        int y = (int) (nHeight/2 - obj.ptY*scale);

        return new RectF(x-mRectRange/2, y-mRectRange/2, x+mRectRange/2,y+mRectRange/2);
    }


    double nLenStart2Touch = 0;
    int xStart2TouchPos = 0;
    int yStart2TouchPos = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int nCnt = event.getPointerCount();
        int n = event.getAction();
        double dirscale = 0.0;

        if( (event.getAction()&MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN && 2 == nCnt) {
            int xlen = Math.abs((int) event.getX(0) - (int) event.getX(1));
            int ylen = Math.abs((int) event.getY(0) - (int) event.getY(1));

            nLenStart2Touch = Math.sqrt((double)xlen*xlen + (double)ylen * ylen);
        }
        else if( (event.getAction()&MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP  && 2 == nCnt)
        {
            int xlen = Math.abs((int)event.getX(0) - (int)event.getX(1));
            int ylen = Math.abs((int)event.getY(0) - (int)event.getY(1));

            int xEnd = ((int)event.getX(0) + (int)event.getX(1))/2;
            int yEnd = ((int)event.getY(0) + (int)event.getY(1))/2;

            double nLenEnd = Math.sqrt((double)xlen*xlen + (double)ylen * ylen);

            if( nLenStart2Touch == 0)
            {
                return true;
            }

            if(nLenEnd > nLenStart2Touch) {
                dirscale = Math.sqrt(nLenEnd/nLenStart2Touch);
                scale = scale + Math.abs(dirscale -1);
                mHandler.sendEmptyMessage(MSG_INVALIDATE);
            }
            else {
                dirscale = Math.sqrt(nLenEnd / nLenStart2Touch);
                scale = scale - Math.abs(dirscale -1);
                mHandler.sendEmptyMessage(MSG_INVALIDATE);
            }

            nLenStart2Touch = 0;
        }
        else if( (event.getAction()&MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE  && 2 == nCnt)
        {
            int xlen = Math.abs((int)event.getX(0) - (int)event.getX(1));
            int ylen = Math.abs((int)event.getY(0) - (int)event.getY(1));

            int xEnd = ((int)event.getX(0) + (int)event.getX(1))/2;
            int yEnd = ((int)event.getY(0) + (int)event.getY(1))/2;

            double nLenEnd = Math.sqrt((double)xlen*xlen + (double)ylen * ylen);

            if( nLenStart2Touch == 0)
            {
                return true;
            }

            if(nLenEnd > nLenStart2Touch) {
                dirscale = Math.sqrt(nLenEnd/nLenStart2Touch);
                scale = scale + Math.abs(dirscale -1);
                mHandler.sendEmptyMessage(MSG_INVALIDATE);
            }
            else {
                dirscale = Math.sqrt(nLenEnd / nLenStart2Touch);
                scale = scale - Math.abs(dirscale -1);
                mHandler.sendEmptyMessage(MSG_INVALIDATE);
            }

            nLenStart2Touch = nLenEnd;
        }
        else
        {
            nLenStart2Touch = 0;
        }

        return true;
    }
}
